package com.boot2.core.dao.jpa;

import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @ClassName: Criteria
 * @description: 查询条件容器
 * @author zhangweilin
 * @date 2017年12月27日 上午11:13:32
 *
 * @param <T>
 */
public class Criteria<T> implements Specification<T> {
	private List<Criterion> criterionList = new ArrayList<Criterion>();

	@Override
	public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
		if (!criterionList.isEmpty()) {
			List<Predicate> predicates = new ArrayList<Predicate>();
			criterionList.forEach(e -> predicates.add(e.toPredicate(root, query, builder)));
			// 将所有条件用 and 联合起来
			if (predicates.size() > 0) {
				return builder.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}
		return builder.conjunction();
	}

	/**
	 * 增加简单条件表达式
	 * 
	 * @param criterion
	 */
	public void add(Criterion criterion) {
		if (criterion != null) {
			criterionList.add(criterion);
		}
	}

	public List<Criterion> getCriterionList() {
		return this.criterionList;
	}
}